package com.syscom.server.hub.listener;

import java.io.IOException;

import org.apache.log4j.Logger;

import com.syscom.safe.tcplink.client.api.PushMessageListener;
import com.syscom.safe.wac.buf.SacInputBuffer;
import com.syscom.sar.server.cache.safeCache.vo.QuotaBrokerCacheVo;
import com.syscom.server.cache.safeCache.vo.RuleQtaHandleCacheVo;
import com.syscom.server.constant.CacheConstant;
import com.syscom.server.constant.QDCodeConstant;
import com.syscom.server.qd.cacheManager.RuleQtaCacheManager;
import com.syscom.shared.constant.NofMsgConstant;

public class HubPushMsgHandler implements PushMessageListener {
	
	private static Logger mLogger = Logger.getLogger(HubPushMsgHandler.class.getName());

	public void onPushMessage(long seqNo, String topicName, String rid, byte[] msg) {
		mLogger.info("Receive Msg, Topic: <" + topicName + "> , rid: <" + rid + "> , Data: [" + new String(msg) + "]");
		
		if (NofMsgConstant.CACHE_NOTIFY_T.equals(topicName)) {
			cacheNotify(msg);
		}
	}
	
	private void cacheNotify(byte[] bMsg) {
		SacInputBuffer sIn = new SacInputBuffer(bMsg);
		
		// 拆開MGX發送格式
		try {
			String sNotifyType = sIn.readAutoString();
			String sCacheType = sIn.readAutoString();
			String sKey = sIn.readAutoString();
			
			if(CacheConstant.QTA_HANDLE_CACHE.equals(sCacheType)) {
				// 全面檢查
				
			} 
			else if(CacheConstant.QUOTA_BROKER_CACHE.equals(sCacheType)) {
				if(QDCodeConstant.CACHE_NOTIFY_UPDATE.equals(sNotifyType)) {
					QuotaBrokerCacheVo quotaBrokerCacheVo = new QuotaBrokerCacheVo();
					quotaBrokerCacheVo.parseInBuffer(sIn);
					
					RuleQtaHandleCacheVo ruleQtaHandleCacheVo = new RuleQtaHandleCacheVo();
					ruleQtaHandleCacheVo.setRuleId(quotaBrokerCacheVo.getRuleId());
					ruleQtaHandleCacheVo.setProdId(quotaBrokerCacheVo.getProdId());
					ruleQtaHandleCacheVo.setWarnQuota(quotaBrokerCacheVo.getWarnQuota());
					ruleQtaHandleCacheVo.setSubQuota(quotaBrokerCacheVo.getSubQuota());
					ruleQtaHandleCacheVo.setRejQuota(quotaBrokerCacheVo.getRejQuota());
					
					RuleQtaCacheManager.getInstance().updateZoomRuleQtaHandleCacheVoByNotify(ruleQtaHandleCacheVo);
				}
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
}
